var searchnum = 1000;
appCtrl.controller('GoodsCtrl', function($scope, $rootScope, $state, UtilsService) {
    if (!$rootScope.dist) {
      $rootScope.$broadcast('loading:showMessage', {
        message: '请选择小区'
      });
      $state.transitionTo('district.list');
      return;
    }

  })
  .controller('GoodsSaledetailCtrl', function($scope, $rootScope, $state, $stateParams, $ionicSlideBoxDelegate, $interval, $timeout, $ionicScrollDelegate, GoodsService, UtilsService, UserService) {
    // $scope.height1 = 4000;
    // var box1 = document.getElementById('saledetail-view');
    // var prey = 0;
    // var starty = 0;
    // var dist = 0;
    //
    // setTimeout(function () {
    //   box1.addEventListener('touchstart', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
    //     starty = parseInt(touchobj.clientY); // get x position of touch point relative to left edge of browser
    //     prey = starty;
    //     // statusdiv.innerHTML = 'Status: touchstart<br> ClientX: ' + startx + 'px'
    //     // console.log('starty' + starty);
    //     e.preventDefault();
    //   }, false);
    //
    //   box1.addEventListener('touchmove', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
    //     var dist = parseInt(touchobj.clientY) - prey;
    //     // statusdiv.innerHTML = 'Status: touchmove<br> Horizontal distance traveled: ' + dist + 'px'
    //     // console.log(dist);
    //     $ionicScrollDelegate.scrollTo($ionicScrollDelegate.getScrollPosition().left, $ionicScrollDelegate.getScrollPosition().top - dist);
    //     prey = parseInt(touchobj.clientY);
    //     e.preventDefault();
    //   }, false);
    //
    //   box1.addEventListener('touchend', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
    //     // statusdiv.innerHTML = 'Status: touchend<br> Resting x coordinate: ' + touchobj.clientX + 'px'
    //     // console.log(touchobj);
    //     e.preventDefault();
    //   }, false);
    // }, 1000);
    $scope.dist = $rootScope.dist;

    $scope.refresh = function() {

      GoodsService.getSaleDetail({
        id: $stateParams.id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.goods = response.data.product;
          $ionicSlideBoxDelegate.update();
          $ionicScrollDelegate.resize()

          // var stop = $interval(function() {
          //   // $scope.height1 = window.innerHeight;
          //   // console.log(window.innerHeight);
          //   // console.log(document.body.scrollHeight);
          //   // console.log(document.body.clientHeight);
          //   var ele = document.getElementById('goodssale-last');
          //   $scope.height1 = ele.offsetTop + 50;
          //   $ionicScrollDelegate.resize();
          //   // console.log($scope.height1);
          // }, 2000);
          //
          // $scope.stopFight = function() {
          //   if (angular.isDefined(stop)) {
          //     $interval.cancel(stop);
          //     stop = undefined;
          //   }
          // };
          //
          // $scope.$on('$destroy', function() {
          //   // Make sure that the interval is destroyed too
          //   $scope.stopFight();
          // });
        }
      });
      $scope.goods = {};

      $scope.addCart = function() {
        if (UtilsService.isLogin()) {
          UserService.addToCart({
            product_id: $stateParams.id,
            product_discount_id: $scope.goods.product_discount_id
          }).$promise.then(function(response) {
            if (UtilsService.isResponseOk(response)) {
              $rootScope.$broadcast('loading:showMessage', {
                message: '加入购物车成功'
              });
            }
          });

        } else {
          $rootScope.$broadcast('loading:showMessage', {
            message: '尚未登录'
          });
        }
      }

      GoodsService.getCommentCount({
        id: $stateParams.id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.commentcount = response.data.count;
          $scope.rate = response.data.score;
        }
      });
    }

    $scope.goBack = function() {
      UtilsService.goBack();
    }

    $scope.flush = function() {
      $ionicScrollDelegate.resize()
    }

    $scope.refresh()
  })
  .controller('GoodsDetailCtrl', function($scope, $rootScope, $state, $stateParams, $ionicSlideBoxDelegate, $ionicScrollDelegate, $timeout, $interval, GoodsService, UtilsService, UserService) {

    $scope.dist = $rootScope.dist;

    GoodsService.getCommentCount({
      id: $stateParams.id
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.commentcount = response.data.count;
        $scope.rate = response.data.score;
      }
    });

    $scope.addCart = function() {
      if (UtilsService.isLogin()) {
        UserService.addToCart({
          product_id: $stateParams.id
        }).$promise.then(function(response) {
          if (UtilsService.isResponseOk(response)) {
            $rootScope.$broadcast('loading:showMessage', {
              message: '加入购物车成功'
            });
          }
        });
      } else {
        $rootScope.$broadcast('loading:showMessage', {
          message: '未登录'
        });
      }
    }

    $scope.goBack = function() {
      UtilsService.goBack();
    }

    $scope.refresh = function() {
      GoodsService.get({
        id: $stateParams.id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.goods = response.data.product;
          $ionicSlideBoxDelegate.update();
          $scope.$broadcast('scroll.refreshComplete');
          $ionicScrollDelegate.resize()

          // var before;
          // var stop = $interval(function() {
          //   // $scope.height1 = window.innerHeight;
          //   // console.log(window.innerHeight);
          //   // console.log(document.body.scrollHeight);
          //   // console.log(document.body.clientHeight);
          //   var ele = document.getElementById('goods-last');
          //   $scope.height1 = ele.offsetTop || window.innerHeight + 50;
          //   // console.log(ele.offsetTop || window.innerHeight);
          //
          // }, 1000);
          //
          // $scope.stopFight = function() {
          //   if (angular.isDefined(stop)) {
          //     $interval.cancel(stop);
          //     stop = undefined;
          //   }
          // };
          //
          // $scope.$on('$destroy', function() {
          //   // Make sure that the interval is destroyed too
          //   $scope.stopFight();
          // });
        }
      });

      GoodsService.getCommentCount({
        id: $stateParams.id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.commentcount = response.data.count;
          $scope.rate = response.data.score;
        }
      });
    }
    $scope.flush = function() {
      $ionicScrollDelegate.resize()
    }

    $scope.$on("$ionicView.loaded", function() {
      $scope.refresh()
    })
  })
  .controller('GoodsSearchCtrl', function($scope, $rootScope, $state, $stateParams, ArepoService, UtilsService, UserService) {
    $scope.dist = $rootScope.dist;
    $scope.page = 1;
    $scope.num = searchnum;
    $scope.orderby = 'index';
    $scope.reverse = false;

    // -1 不获取商品，0 获取全部
    if ($stateParams.classid != -1) {
      // 0获取所有
      ArepoService.getGoods({
        id: $rootScope.dist.a_repository_id,
        class_id: $stateParams.classid,
        page: $scope.page,
        num: $scope.num,
        type: $stateParams.type ? $stateParams.type : 3
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {

          $scope.goodslist = response.data.products;
          for (var i in $scope.goodslist) {
            $scope.goodslist[i].kj_price = parseFloat($scope.goodslist[i].kj_price);
            $scope.goodslist[i].sc_price = parseFloat($scope.goodslist[i].sc_price);
            $scope.goodslist[i].amount = parseFloat($scope.goodslist[i].amount);
            $scope.goodslist[i].index = parseFloat($scope.goodslist[i].index);
          }
        }
      });
    }

    $scope.cartproducts = [];
    $scope.count = 0;

    $scope.search = function(key) {
      if (!key) {
        return;
      }

      ArepoService.searchGoods({
        id: $scope.dist.a_repository_id,
        class_id: $stateParams.classid < 0 ? 0 : $stateParams.classid,
        type: $stateParams.type ? $stateParams.type : 3,
        page: $scope.page,
        num: $scope.num,
        key: key
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.goodslist = response.data.products;
        }
      });
    }

    $scope.goBack = function() {
      UtilsService.goBack();
    }
    $scope.addCart = function(goods) {
      if (UtilsService.isLogin()) {
        UserService.addToCart({
          product_id: goods.product_id
        }).$promise.then(function(response) {
          if (UtilsService.isResponseOk(response)) {
            // $rootScope.$broadcast('cart')
            // $scope.cartproducts.push(goods);
            $rootScope.$broadcast('loading:showMessage', {
              message: '加入购物车成功'
            });
            $scope.count++;
          }
        });
      } else {
        $rootScope.$broadcast('loading:showMessage', {
          message: '未登录'
        });
      }
    }

    $scope.getCount = function() {
      $scope.count = 0;
      for (var p in $scope.cartproducts) {
        $scope.count += parseFloat($scope.cartproducts[p].num);
      }
    }

    $scope.changeToGoods = function(goods) {
      $state.transitionTo('goods.detail', {
        id: goods.product_id
      });
    }

    if (UtilsService.isLogin()) {
      UserService.getCartCount().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.count = response.data.count;
        }
      });
    }
  })
  .controller('GoodsCursaleCtrl', function($scope, $rootScope, $state, $stateParams, ArepoService, UtilsService, UserService, ProductClassService) {
    ArepoService.getSales({
      id: UtilsService.getAid(),
      num: searchnum
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.goodslist = response.data.products;
      }
    });

    $scope.changeToGoods = function(goods) {
      $state.transitionTo('goods.saledetail', {
        id: goods.product_id
      });
    }

    $scope.addCart = function(goods) {
      if (UtilsService.isLogin()) {
        UserService.addToCart({
          product_id: goods.product_id,
          product_discount_id: goods.product_discount_id
        }).$promise.then(function(response) {
          if (UtilsService.isResponseOk(response)) {
            // $rootScope.$broadcast('cart')
            // $scope.cartproducts.push(goods);
            $rootScope.$broadcast('loading:showMessage', {
              message: '加入购物车成功'
            });
            $scope.count++;
          }
        });
      } else {
        $rootScope.$broadcast('loading:showMessage', {
          message: '未登录'
        });
      }
    }

    $scope.getCount = function() {
      $scope.count = 0;
      for (var p in $scope.cartproducts) {
        $scope.count += parseInt($scope.cartproducts[p].num);
      }
    }

    if (UtilsService.isLogin()) {
      UserService.getCartCount().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.count = response.data.count;
        }
      });
    }

  })
  .controller('GoodsClassCtrl', function($scope, $rootScope, $state, $stateParams, ArepoService, UtilsService, UserService, ProductClassService) {
    $scope.dist = $rootScope.dist;
    $scope.page = 1;
    $scope.num = searchnum;

    ProductClassService.get({
      class_id: $stateParams.classid
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.curclass = response.data.class;
      }
    });
    $scope.showlist = [];
    ArepoService.getGoods({
      id: $scope.dist.a_repository_id,
      class_id: $stateParams.classid,
      page: $scope.page,
      num: $scope.num,
      type: $stateParams.type
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.goodslist = response.data.products;
        var length = $scope.goodslist.length;
        for (var i = 0; i < length; i += 2) {
          var temp = [];
          temp.push($scope.goodslist[i]);
          if (i + 1 < length) {
            temp.push($scope.goodslist[i + 1]);
          }
          $scope.showlist.push(temp);
        }
      }
    });

    $scope.cartproducts = [];
    $scope.count = 0;

    $scope.addCart = function(goods) {
      if (UtilsService.isLogin()) {
        UserService.addToCart({
          product_id: goods.product_id
        }).$promise.then(function(response) {
          if (UtilsService.isResponseOk(response)) {
            // $rootScope.$broadcast('cart')
            // $scope.cartproducts.push(goods);
            $rootScope.$broadcast('loading:showMessage', {
              message: '加入购物车成功'
            });
            $scope.count++;
          }
        });
      } else {
        $rootScope.$broadcast('loading:showMessage', {
          message: '未登录'
        });
      }
    }


    $scope.getCount = function() {
      $scope.count = 0;
      for (var p in $scope.cartproducts) {
        $scope.count += parseInt($scope.cartproducts[p].num);
      }
    }

    $scope.changeToGoods = function(goods) {
      $state.transitionTo('goods.detail', {
        id: goods.product_id
      });
    }

    $scope.goBack = function() {
      UtilsService.goBack();
    }


    if (UtilsService.isLogin()) {
      UserService.getCartCount().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.count = response.data.count;
        }
      });
    }
  })
  .controller('GoodsCommentsCtrl', function($scope, $rootScope, $stateParams, UtilsService, GoodsService) {
    $scope.vm = this
    var _this = this

    this.goBack = function(){
      UtilsService.goBack()
    }
    GoodsService.getComments({
      id: $stateParams.id
    }).$promise.then(function(res) {
      if (UtilsService.isResponseOk(res)) {
        _this.comments = res.data.comments
      }
    })

  })

;
